<template>
  <view class="container">
    <scroll-view class="content" scroll-y>
      <!-- 用户信息 -->
      <view class="user-section">
        <view class="user-info">
          <u-avatar :src="post?.userInfo?.avatar" size="48"></u-avatar>
          <view class="user-details">
            <text class="nickname">{{ post?.userInfo?.nickname }}</text>
            <text class="time">{{ formatRelativeTime(post?.createdAt || '') }}</text>
          </view>
        </view>
        <view class="category-tag">
          <text>{{ post?.categoryInfo?.name }}</text>
        </view>
      </view>

      <!-- 媒体内容 -->
      <view v-if="post?.mediaUrls && post.mediaUrls.length > 0" class="media-section">
        <swiper v-if="post.mediaType === 'image'" class="media-swiper" indicator-dots>
          <swiper-item v-for="(url, index) in post.mediaUrls" :key="index">
            <image :src="url" class="media-image" mode="aspectFill" @click="previewImages(index)" />
          </swiper-item>
        </swiper>
        <video
          v-else-if="post.mediaType === 'video'"
          :src="post.mediaUrls[0]"
          class="media-video"
          controls
        />
      </view>

      <!-- 标题和内容 -->
      <view class="content-section">
        <text v-if="post?.title" class="title">{{ post.title }}</text>
        <text class="content-text">{{ post?.content }}</text>
      </view>

      <!-- 价格信息 -->
      <view v-if="post?.priceInfo" class="price-section">
        <text class="price">¥{{ post.priceInfo.price }}</text>
        <text v-if="post.priceInfo.unit" class="unit">/{{ post.priceInfo.unit }}</text>
        <text v-if="post.priceInfo.negotiable" class="negotiable">可议价</text>
      </view>

      <!-- 位置信息 -->
      <view class="info-section">
        <view class="info-item">
          <u-icon name="map" size="20" color="#5677fc"></u-icon>
          <text class="ml-sm">{{ post?.locationInfo?.address }}</text>
        </view>
        <view class="info-item">
          <u-icon name="clock" size="20" color="#5677fc"></u-icon>
          <text class="ml-sm">发布于 {{ formatTime(post?.createdAt || '', 'YYYY-MM-DD HH:mm') }}</text>
        </view>
        <view class="info-item">
          <u-icon name="eye" size="20" color="#5677fc"></u-icon>
          <text class="ml-sm">浏览 {{ post?.viewCount }} 次</text>
        </view>
      </view>

      <!-- 相关推荐 -->
      <view v-if="relatedPosts.length > 0" class="related-section">
        <view class="section-title">相关推荐</view>
        <post-card
          v-for="item in relatedPosts"
          :key="item.id"
          :post="item"
          @click="goToDetail(item.id)"
        />
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="footer">
      <view class="action-group">
        <view class="action-btn" @click="handleLike">
          <u-icon
            :name="post?.isLiked ? 'heart-fill' : 'heart'"
            size="24"
            :color="post?.isLiked ? '#fa3534' : '#666'"
          ></u-icon>
          <text>{{ post?.isLiked ? '已赞' : '点赞' }}</text>
        </view>
        <view class="action-btn" @click="handleCollect">
          <u-icon
            :name="post?.isCollected ? 'star-fill' : 'star'"
            size="24"
            :color="post?.isCollected ? '#ff9900' : '#666'"
          ></u-icon>
          <text>{{ post?.isCollected ? '已收藏' : '收藏' }}</text>
        </view>
        <view class="action-btn" @click="handleShare">
          <u-icon name="share" size="24" color="#666"></u-icon>
          <text>分享</text>
        </view>
      </view>
      <view class="contact-btn" @click="handleContact">
        <text>联系TA</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { Post } from '@/types'
import { postApi } from '@/api'
import { formatRelativeTime, formatTime } from '@/utils/format'
import { previewImage } from '@/utils/common'
import PostCard from '@/pages/index/components/PostCard.vue'

// 状态
const postId = ref<number>(0)
const post = ref<Post | null>(null)
const relatedPosts = ref<Post[]>([])
const loading = ref(false)

// 生命周期
onLoad((options: any) => {
  postId.value = Number(options.id)
  if (postId.value) {
    loadPostDetail()
  }
})

/**
 * 加载详情
 */
const loadPostDetail = async () => {
  if (loading.value) return

  loading.value = true

  try {
    const res = await postApi.getDetail(postId.value)
    post.value = res.post
    relatedPosts.value = res.relatedPosts || []

    // 记录浏览
    postApi.recordView(postId.value).catch(err => {
      console.error('记录浏览失败:', err)
    })
  } catch (err) {
    console.error('加载详情失败:', err)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 预览图片
 */
const previewImages = (currentIndex: number) => {
  if (post.value?.mediaUrls) {
    previewImage(post.value.mediaUrls, currentIndex)
  }
}

/**
 * 点赞
 */
const handleLike = async () => {
  if (!post.value) return

  try {
    if (post.value.isLiked) {
      await postApi.unlike(post.value.id)
      post.value.isLiked = false
      post.value.likeCount--
    } else {
      await postApi.like(post.value.id)
      post.value.isLiked = true
      post.value.likeCount++
    }
  } catch (err) {
    console.error('点赞失败:', err)
  }
}

/**
 * 收藏
 */
const handleCollect = async () => {
  if (!post.value) return

  try {
    if (post.value.isCollected) {
      await postApi.unfavorite(post.value.id)
      post.value.isCollected = false
      uni.showToast({ title: '已取消收藏', icon: 'none' })
    } else {
      await postApi.favorite(post.value.id)
      post.value.isCollected = true
      uni.showToast({ title: '收藏成功', icon: 'success' })
    }
  } catch (err) {
    console.error('收藏失败:', err)
  }
}

/**
 * 分享
 */
const handleShare = () => {
  // #ifdef MP-WEIXIN
  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
  // #endif

  uni.showToast({
    title: '请点击右上角分享',
    icon: 'none'
  })
}

/**
 * 联系
 */
const handleContact = () => {
  if (!post.value) return

  uni.navigateTo({
    url: `/pages/chat/detail?userId=${post.value.userId}&postId=${post.value.id}`
  })
}

/**
 * 跳转到详情
 */
const goToDetail = (id: number) => {
  // 刷新当前页面
  postId.value = id
  post.value = null
  relatedPosts.value = []
  loadPostDetail()

  // 滚动到顶部
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 300
  })
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color-page);
}

.content {
  flex: 1;
  padding-bottom: 120rpx;
}

.user-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-md);
  background-color: var(--bg-color);

  .user-info {
    display: flex;
    align-items: center;

    .user-details {
      margin-left: var(--spacing-sm);
      display: flex;
      flex-direction: column;

      .nickname {
        font-size: 32rpx;
        font-weight: 500;
        color: var(--text-color);
      }

      .time {
        font-size: 24rpx;
        color: var(--text-color-placeholder);
        margin-top: 4rpx;
      }
    }
  }

  .category-tag {
    padding: 8rpx 16rpx;
    background-color: var(--primary-color);
    color: #ffffff;
    font-size: 24rpx;
    border-radius: var(--radius-sm);
  }
}

.media-section {
  margin-top: var(--spacing-sm);

  .media-swiper {
    width: 100%;
    height: 500rpx;

    .media-image {
      width: 100%;
      height: 100%;
    }
  }

  .media-video {
    width: 100%;
    height: 500rpx;
  }
}

.content-section {
  padding: var(--spacing-md);
  background-color: var(--bg-color);
  margin-top: var(--spacing-sm);

  .title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: var(--text-color);
    margin-bottom: var(--spacing-md);
  }

  .content-text {
    font-size: 30rpx;
    line-height: 1.8;
    color: var(--text-color-secondary);
  }
}

.price-section {
  display: flex;
  align-items: baseline;
  padding: var(--spacing-md);
  background-color: var(--bg-color);
  margin-top: var(--spacing-sm);

  .price {
    font-size: 48rpx;
    font-weight: bold;
    color: var(--error-color);
  }

  .unit {
    font-size: 28rpx;
    color: var(--text-color-secondary);
    margin-left: 8rpx;
  }

  .negotiable {
    font-size: 24rpx;
    color: var(--warning-color);
    margin-left: var(--spacing-sm);
    padding: 4rpx 12rpx;
    background-color: rgba(255, 153, 0, 0.1);
    border-radius: 8rpx;
  }
}

.info-section {
  padding: var(--spacing-md);
  background-color: var(--bg-color);
  margin-top: var(--spacing-sm);

  .info-item {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: var(--text-color-secondary);
    margin-bottom: var(--spacing-md);

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.related-section {
  padding: var(--spacing-md);
  margin-top: var(--spacing-sm);

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: var(--text-color);
    margin-bottom: var(--spacing-md);
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-md);
  background-color: var(--bg-color);
  border-top: 1rpx solid var(--border-color-light);
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);

  .action-group {
    display: flex;
    gap: var(--spacing-lg);

    .action-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8rpx;

      text {
        font-size: 24rpx;
        color: var(--text-color-secondary);
      }
    }
  }

  .contact-btn {
    flex: 1;
    margin-left: var(--spacing-lg);
    padding: 20rpx 0;
    background: linear-gradient(135deg, var(--primary-color) 0%, #4166f5 100%);
    color: #ffffff;
    font-size: 32rpx;
    font-weight: 500;
    text-align: center;
    border-radius: var(--radius-round);
  }
}
</style>
